<template>
    <div class="e-form">
        <BillTop title="维修保养记录编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="维保明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.maintenanceLog" label-width="180px" :rules="rules">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="维保编号：">
                                            <span>{{ formData.maintenanceLog.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="记录日期：" prop="billDate">
                                            <el-date-picker
                                                v-model="formData.maintenanceLog.billDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="维保类型：" prop="maintenanceType">
                                            <el-select v-model="formData.maintenanceLog.maintenanceType"  @change="selectMaintenanceType">
                                                <el-option :value="+item.value" :label="item.label" v-for="item,index in maintenanceType" :key="index" ></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="维保计划：" prop="maintenancePlan">
                                            <el-input v-model="formData.maintenanceLog.maintenancePlan"  readonly>
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectMaintenancePlan"></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="维保单位：" prop="maintenanceUnit">
                                            <el-input v-model="formData.maintenanceLog.maintenanceUnit">
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ formData.maintenanceLog.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="送修/养日期：" prop="sendToRepairTime">
                                            <el-date-picker
                                                v-model="formData.maintenanceLog.sendToRepairTime"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="完修/养日期：" prop="completeRepairTime">
                                            <el-date-picker
                                                v-model="formData.maintenanceLog.completeRepairTime"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="维保费（元）：">
                                            <span>{{ formData.maintenanceLog.maintenancePrice }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="辅助设备费（元）：">
                                            <span>{{ formData.maintenanceLog.auxiliaryFee }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="材料费（元）：">
                                            <span>{{ formData.maintenanceLog.materialsPrice }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="人工费（元）：">
                                            <span>{{ formData.maintenanceLog.manpowerPrice }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="记录人：">
                                            <span>{{ formData.maintenanceLog.noteTaker }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{ statusLable(formData.maintenanceLog.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">设备维修清单</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button  class="btn-greenYellow" @click="selectEquip">选择设备</el-button>
                                        <el-button  class="btn-delete" @click="deletePlanList" v-if="isBatch[0].flag">批量删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('planDetail')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[0].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <span>{{res}}</span>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="maintenanceLogDtlListCopy"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                @row-click="rowClick"
                                :row-style="rowStyle"
                                v-sortTable="{ 'tableData': maintenanceLogDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column type="selection" width="55" align="center" v-if="isBatch[0].flag">
                                </el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handlePlanDetailDelete(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentNo"
                                    label="设备编号"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    label="设备名称"
                                    min-width="200"
                                    show-overflow-tooltipd
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="categoryName"
                                    label="设备类别"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="manufacturer"
                                    label="生产厂商"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="useNum"
                                    label="累计使用数"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="maintenanceFee"
                                    label="维保费用（元）"
                                    width="130"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialsFee"
                                    label="材料费（元）"
                                    width="130"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="artificialFee"
                                    label="人工费（元）"
                                    width="130"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="assistFee"
                                    label="辅助设备费（元）"
                                    width="150"
                                    align="right"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.assistFee" @input="curStateChange(row)" clearable
                                        v-enter-float="{
                                            set: row,
                                            key: 'assistFee'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="info"
                                    label="维保内容"
                                    align="center"
                                    min-width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.info" @input="curStateChange(row)" clearable></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div class="tabs-title">设备维修内容</div>
                        <el-tabs :class="'childTab ' + childTabClass" tab-position="left" v-model="tabsNameChild" @tab-click="onChangeTab">
                            <el-tab-pane label="物资明细" name="materialDetails" :disabled="clickTabFlag"></el-tab-pane>
                            <el-tab-pane label="技术参数" name="technicalParameter" :disabled="clickTabFlag"></el-tab-pane>
                            <el-tab-pane label="人工费" name="laborCost" :disabled="clickTabFlag"></el-tab-pane>
                            <div>
                                <div id="materialDetailsCon" class="con">
                                    <div class="tabs-title" id="materialDetails">物资明细</div>
                                    <div class="e-table">
                                        <div class="top">
                                            <div class="left">
                                                <div>
                                                    <el-button  class="btn-greenYellow" @click="selectStoreIssue">从机械发料引入</el-button>
                                                    <el-button  class="btn-greenYellow" @click="selectMaterials">从物资库引入</el-button>
                                                    <el-button  class="btn-delete"  @click="deletePlanChildList('materialsDtlList','materialDtlId')" v-if="isBatch[1].flag">批量删除</el-button>
                                                </div>
                                                <div class="batchBox" @click="batchOperation('materialDetails')">
                                                    <img class="batchicon" src="@/assets/piliang.png">
                                                    <span class="batchfont">{{isBatch[1].batch}}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="errorMsg" v-if="errorMaterialMsg.length>0">
                                            <span v-for="item,index in errorMaterialMsg" :key="index">
                                                {{item}}
                                            </span>
                                        </div>
                                        <el-table
                                            class="table"
                                            ref="planTablematerialsDtlList"
                                            :data="currentMaintenanceRow.materialsDtlDTO.materialsDtlList"
                                            border
                                            style="width: 100%"
                                            @selection-change="planTableChildSelect($event,'materialsDtlList')"
                                            :row-class-name="materialsRowClass"
                                            v-sortTable="{ 'tableData': currentMaintenanceRow.materialsDtlDTO.materialsDtlList, '_this': this, 'ref': 'planTablematerialsDtlList' }"
                                        >
                                            <el-table-column type="selection" width="55" align="center" v-if="isBatch[1].flag">
                                            </el-table-column>
                                            <el-table-column fixed label="操作" width="70">
                                                <template slot-scope="{ row,$index }">
                                                    <div class="handle">
                                                        <div style=" cursor: pointer;">
                                                            <img src="@/assets/btn/delete.png"  @click="handleDelete(row,$index,'materialsDtlList','materialDtlId')">
                                                        </div>
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="materialName"
                                                label="物资名称"
                                                min-width="200"
                                                show-overflow-tooltip
                                                align="center"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="specification"
                                                label="规格"
                                                min-width="200"
                                                show-overflow-tooltip
                                                align="center"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="unit"
                                                label="单位"
                                                width="130"
                                                align="center"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="num"
                                                label="数量"
                                                width="170"
                                                align="center"
                                            >
                                                <template slot-scope="{ row }">
                                                    <el-input v-model="row.num" clearable
                                                    @input="curMaterialsDtlStateChange(row)"
                                                    v-enter-float2="{
                                                        set: row,
                                                        key: 'num'
                                                    }"></el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="price"
                                                label="单价"
                                                width="150"
                                                align="center"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="sum"
                                                label="金额（元）"
                                                width="170"
                                                align="center"
                                            >
                                                <template slot-scope="{ row }">
                                                    <el-input v-model="row.sum" clearable
                                                    @input="curMaterialsDtlStateChange(row,'materialsDtlList')"
                                                    v-enter-float="{
                                                        set: row,
                                                        key: 'sum'
                                                    }"></el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="replaceReason"
                                                label="更换原因"
                                                width="170"
                                                align="center"
                                            >
                                                <template slot-scope="{ row }">
                                                    <el-input v-model="row.replaceReason"  @input="curMaterialsDtlStateChange(row)" clearable></el-input>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>

                                <div id="technicalParameterCon" class="con">
                                    <div class="tabs-title" id="technicalParameter">技术参数</div>
                                    <div class="e-table">
                                        <div class="top">
                                            <div class="left">
                                                <div>
                                                    <el-button  class="btn-greenYellow"  @click="addPlanChildInfo('technologyParameterList')">新增</el-button>
                                                    <el-button  class="btn-delete"  @click="deletePlanChildList('technologyParameterList','technologyParameterId')" v-if="isBatch[2].flag">批量删除</el-button>
                                                </div>
                                                <div class="batchBox" @click="batchOperation('technicalParameter')">
                                                    <img class="batchicon" src="@/assets/piliang.png">
                                                    <span class="batchfont">{{isBatch[2].batch}}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="errorMsg" v-if="errortechnicalMsg.length>0">
                                            <span v-for="item,index in errortechnicalMsg" :key="index">
                                                {{item}}
                                            </span>
                                        </div>
                                        <el-table
                                            class="table"
                                            ref="planTabletechnologyParameterList"
                                            :data="currentMaintenanceRow.materialsDtlDTO.technologyParameterList"
                                            border
                                            style="width: 100%"
                                            @selection-change="planTableChildSelect($event,'technologyParameterList')"
                                            :row-class-name="technologyRowClass"
                                            v-sortTable="{ 'tableData': currentMaintenanceRow.materialsDtlDTO.technologyParameterList, '_this': this, 'ref': 'planTabletechnologyParameterList' }"
                                        >
                                            <el-table-column type="selection" width="55" align="center" v-if="isBatch[2].flag">
                                            </el-table-column>
                                            <el-table-column fixed label="操作" width="70">
                                                <template slot-scope="{ row,$index }">
                                                    <div class="handle">
                                                        <div style=" cursor: pointer;">
                                                            <img src="@/assets/btn/delete.png"  @click="handleDelete(row,$index,'technologyParameterList','technologyParameterId')">
                                                        </div>
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="bigItemName"
                                                label="大件名称"
                                                align="center"
                                                min-width="200"
                                            >
                                                <template slot-scope="{ row }">
                                                    <el-input v-model="row.bigItemName" @input="curTechnologyStateChange(row)" clearable></el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="leaveFactoryNo"
                                                label="出厂编号"
                                                min-width="200"
                                                align="center"
                                            >
                                                <template slot-scope="{ row }">
                                                    <el-input v-model="row.leaveFactoryNo" @input="curTechnologyStateChange(row)" clearable></el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="manufactureUnit"
                                                label="制造单位"
                                                min-width="200"
                                                align="center"
                                            >
                                                <template slot-scope="{ row }">
                                                    <el-input v-model="row.manufactureUnit" @input="curTechnologyStateChange(row)" clearable></el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="producedDate"
                                                label="生产日期"
                                                width="170"
                                                align="center"
                                            >
                                                <template slot-scope="{ row }">
                                                    <el-date-picker
                                                        v-model="row.producedDate"
                                                        @input="curTechnologyStateChange(row)"
                                                        type="date"
                                                        placeholder="选择日期"
                                                        value-format="yyyy-MM-dd"
                                                        :clearable="false"
                                                    >
                                                    </el-date-picker>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>

                                <div id="laborCostCon" class="con">
                                    <div class="tabs-title" id="laborCost">人工费</div>
                                    <div class="e-table">
                                        <div class="top">
                                            <div class="left">
                                                <div>
                                                    <el-button  class="btn-greenYellow" @click="addPlanChildInfo('artificialFeeList')">新增</el-button>
                                                    <el-button  class="btn-delete"  @click="deletePlanChildList('artificialFeeList','artificialFeeId')" v-if="isBatch[3].flag">批量删除</el-button>
                                                </div>
                                                <div class="batchBox" @click="batchOperation('laborCost')">
                                                    <img class="batchicon" src="@/assets/piliang.png">
                                                    <span class="batchfont">{{isBatch[3].batch}}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="errorMsg" v-if="errorArtificialMsg.length>0">
                                            <span v-for="item,index in errorArtificialMsg" :key="index">
                                                {{item}}
                                            </span>
                                        </div>
                                        <el-table
                                            class="table"
                                            ref="planTableartificialFeeList"
                                            :data="currentMaintenanceRow.materialsDtlDTO.artificialFeeList"
                                            border
                                            style="width: 100%"
                                            @selection-change="planTableChildSelect($event,'artificialFeeList')"
                                            :row-class-name="artificialFeeRowClass"
                                            v-sortTable="{ 'tableData': currentMaintenanceRow.materialsDtlDTO.artificialFeeList, '_this': this, 'ref': 'planTableartificialFeeList' }"
                                        >
                                            <el-table-column type="selection" width="55" align="center" v-if="isBatch[3].flag">
                                            </el-table-column>
                                            <el-table-column fixed label="操作" width="70">
                                                <template slot-scope="{ row,$index }">
                                                    <div class="handle">
                                                        <div style=" cursor: pointer;">
                                                            <img src="@/assets/btn/delete.png"  @click="handleDelete(row,$index,'artificialFeeList','artificialFeeId')">
                                                        </div>
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="maintenanceProject"
                                                label="维保项目"
                                                align="center"
                                                min-width="200"
                                            >
                                                <template slot-scope="{ row }">
                                                    <el-input v-model="row.maintenanceProject"  @input="curManpowerStateChange(row)" clearable></el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="fee"
                                                label="人工费（元）"
                                                width="250"
                                                align="center"
                                            >
                                                <template slot-scope="{ row }">
                                                    <el-input v-model="row.fee" clearable
                                                    @input="curManpowerStateChange(row,'artificialFeeList')"
                                                    v-enter-float="{
                                                        set: row,
                                                        key: 'fee'
                                                    }"></el-input>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>
                            </div>
                        </el-tabs>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="facilitymanagement" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="3006"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.maintenanceLog.state" @exas="exas" :founderId="formData.maintenanceLog.founderId" />
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/dailyManagement.js'
//import { formatDate } from '@/utils/common.js'
import { hideLoading, showLoading } from '@/utils/common'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { history, getCurrentUnitInfo } from '@/api/equip/dailyManagementAudit.js'
import { exas, saveAll, submitCommit } from '@/pages/equipment/components/auditHistory/equipCom.js'
import { selectMaintenance, categoryLibrary, selectMaintenanceDtl, removeRepetition, selectStoreIssue } from '@/api/equip/popupCallback.js'
import count from '@/api/equip/dailyManagementCount.js'
export default {
    data () {
        return {
            res: '',
            isBatch: [
                {
                    flag: true,
                    batch: '进入批量管理'
                },
                {
                    flag: true,
                    batch: '进入批量管理'
                },
                {
                    flag: true,
                    batch: '进入批量管理'
                },
                {
                    flag: true,
                    batch: '进入批量管理'
                },
            ],
            tabsName: 'baseInfo',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            selectEquipVisible: false,
            tableData: [],
            formData: {
                //基础信息
                'maintenanceLog': {
                    'auxiliaryFee': 0,
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'completeRepairTime': '',
                    'equipmentName': '',
                    'equipmentNo': '',
                    'equipmentPrice': 0,
                    'facilityInitializeId': '',
                    'founderId': '',
                    'founderName': '',
                    'isInit': true,
                    'maintenanceDetails': '',
                    'maintenancePlan': '',
                    'maintenancePrice': 0,
                    'maintenanceType': '',
                    'maintenanceUnit': '',
                    'manpowerPrice': 0,
                    'materialsPrice': 0,
                    'noteTaker': '',
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDescription': '',
                    'nullifyReason': '',
                    'operateState': 0,
                    'orgId': '',
                    'orgName': '',
                    'remarks': '',
                    'sendToRepairTime': '',
                    'specifications': '',
                    'state': 0,
                    'workId': '',
                    'maintenancePlanId': ''
                },
            },
            rules: {
                billDate: [
                    { required: true, message: '请选择记录日期', trigger: 'change' },
                ],
                maintenancePlan: [
                    { required: true, message: '请选择维保计划', trigger: 'change'  },
                ],
                maintenanceType: [
                    { required: true, message: '请选择维保类型', trigger: 'change'  },
                ],
                maintenanceUnit: [
                    { required: true, message: '请填写维保单位', trigger: 'change'  },
                ],
                sendToRepairTime: [
                    { required: true, message: '请选择送修/养日期', trigger: 'change'  },
                    { validator: (rule, value, callback)=>{
                        const sendToRepairTime = new Date(this.formData.maintenanceLog.sendToRepairTime).getTime() //送修/养日期
                        const  completeRepairTime = new Date(this.formData.maintenanceLog.completeRepairTime).getTime() //完修/养日期
                        if(this.formData.maintenanceLog.sendToRepairTime) {
                            if(sendToRepairTime > completeRepairTime) {
                                callback(new Error('送修/养日期不能大于完修/养日期！'))
                            }else{
                                callback()
                            }
                        }else{
                            callback()
                        }
                    }, trigger: 'change' }
                ],
                completeRepairTime: [
                    { required: true, message: '请选择完修/养日期', trigger: 'change'  },
                    { validator: (rule, value, callback)=>{
                        const sendToRepairTime = new Date(this.formData.maintenanceLog.sendToRepairTime).getTime() //送修/养日期
                        const  completeRepairTime = new Date(this.formData.maintenanceLog.completeRepairTime).getTime() //完修/养日期
                        if(this.formData.maintenanceLog.sendToRepairTime) {
                            if(sendToRepairTime > completeRepairTime) {
                                callback(new Error('完修/养日期不能小于送修/养日期！'))
                            }else{
                                callback()
                            }
                        }else{
                            callback()
                        }
                    }, trigger: 'change' }
                ],
            },
            auditHistoryTable: [], //审核历史
            planSelect: [], //设备维修清单选择项
            maintenanceLogDtlListCopy: [], //设备维修清单
            maintenanceLogDtlList: [],
            onlyID: '', //唯一id
            currentMaintenanceRow: {
                materialsDtlDTO: {
                    materialsDtlList: [], //物资明细
                    artificialFeeList: [], //	人工费
                    technologyParameterList: [], //技术参数
                },
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            errorMaterialMsg: [], //物资明细错误显示
            errortechnicalMsg: [], //技术参数
            errorArtificialMsg: [], //人工费
            isErrorMsg: true, //是否提醒错误信息
            currentRow: {},
            billid: this.$route.query.billid,
            workIndex: 0,
            equipIndex: null, //当前设备维修清单的第几项
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 3006,
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 3006,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            equipmentId: ''
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            maintenanceType: state => state.equip.equipData.maintenanceType, //维保类型
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj ? obj.label : ''
            }
        },
        //当前单据状态
        state () {
            return this.formData.maintenanceLog.state
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        //获取维保类型切换前的值
        'formData.maintenanceLog.maintenanceType': function (newVal, oldVal) {
            this.oldType = oldVal
        },
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    created () {
        this.userId = localStorage.getItem('userId')
        this.getDicValue()
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo',  ['planDetail', 'materialDetails', 'technicalParameter', 'laborCost'], 'attach', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x=>x ===  this.clickId)) {
                this.childTabClass = ''//无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if(item instanceof Array) {
                        const prevHeight = document.getElementById(item[0]).offsetHeight + document.getElementById(item[0]).nextSibling.offsetHeight//因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i)=>{
                            if(i === 0) {
                                return document.getElementById(x).offsetTop
                            }else{
                                return document.getElementById(x).offsetTop + prevHeight + document.getElementById(item[0]).offsetTop
                            }
                        })
                        return arr
                    }else{
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for(let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if ((scrollTop + 1) >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if ((scrollTop + 1) >= item[0]) {
                        curLocal = i
                        break
                    }

                }else{
                    let item = $idsTop[i]
                    if ((scrollTop + 1) >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if(arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            }else{
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index)=>{
                if(item instanceof Array) {
                    let tabNavHeight = document.querySelector('.childTab .el-tabs__nav') ? document.querySelector('.childTab .el-tabs__nav').offsetHeight : 0
                    if((scrollTop + 1) >= ($idsTop[index + 1] - tabNavHeight)) {
                        this.childTabClass = 'childTab2'
                    }
                    else if(scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    }else{
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if(item instanceof Array) {
                    const prevHeight = document.getElementById(item[0]).offsetHeight + document.getElementById(item[0]).nextSibling.offsetHeight//因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i)=>{
                        if(i === 0) {
                            return document.getElementById(x).offsetTop
                        }else{
                            return document.getElementById(x).offsetTop + prevHeight + document.getElementById(item[0]).offsetTop
                        }
                    })
                    return arr
                }else{
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
        this.scorllDtl()
    },
    methods: {
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //是否进入批量操作
        batchOperation (name) {
            switch(name) {
            case 'planDetail':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch[0].flag) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'materialDetails':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if(this.isBatch[1].flag) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            case 'technicalParameter':
                this.isBatch[2].flag = !this.isBatch[2].flag
                if(this.isBatch[2].flag) {
                    this.isBatch[2].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[2].batch = '进入批量管理'
                }
                break
            case 'laborCost':
                this.isBatch[3].flag = !this.isBatch[3].flag
                if(this.isBatch[3].flag) {
                    this.isBatch[3].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[3].batch = '进入批量管理'
                }
                break
            }
        },
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setMaintenanceType')//更新维保类型
        },
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getCurrentUnitInfo(),
                this.getAuditHistory(),
            ]).finally(() => {
                hideLoading()
            })
        },
        getInfo () {
            request.maintenanceRecordsBaseInfo(this.billid).then(res=>{
                this.formData.maintenanceLog = res.maintenanceLog
            })
        },
        getPlanList () {
            request.maintenanceRecordsPlanInfo(this.billid).then(res=>{
                this.maintenanceLogDtlListCopy = []
                res.maintenanceLogDtlList.map(item=>{
                    this.maintenanceLogDtlListCopy.push(item)
                    item.newAdd = false
                })
                this.maintenanceLogDtlList = res.maintenanceLogDtlList
                this.defaultShowFirstLine()
            })
        },
        //默认显示第一行
        defaultShowFirstLine () {
            if(this.maintenanceLogDtlListCopy.length > 0) {
                this.onlyID = this.maintenanceLogDtlListCopy[0].maintenanceLogDtlId //默认选择第一行
                this.currentMaintenanceRow = this.maintenanceLogDtlListCopy[0] //默认显示第一行的数据
            }
        },
        //获取状态按钮
        getCurrentUnitInfo () {
            getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //=============基础信息============
        //清空明细的数据
        clearDetail () {
            this.maintenanceLogDtlListCopy = []
            this.maintenanceLogDtlList.forEach(item=>{
                item.changeType = -1
                //清空子数据
                for(let i in item.materialsDtlDTO) {
                    this.currentMaintenanceRow.materialsDtlDTO[i] = []
                }
            })
        },
        //切换维保类型
        selectMaintenanceType () {
            this.clientPop(
                'info',
                '切换维保类型后，维保计划及明细将被清空，请确认！',
                ()=>{
                    this.formData.maintenanceLog.maintenancePlan = ''
                    this.formData.maintenanceLog.maintenancePlanId = ''
                    this.clearDetail()

                },
                null,
                ()=>{
                    this.formData.maintenanceLog.maintenanceType = this.oldType
                }
            )
        },
        //选择维保计划
        selectMaintenancePlan () {
            if(this.formData.maintenanceLog.maintenanceType === '' || this.formData.maintenanceLog.maintenanceType === null) {
                this.clientPop('err', '请先选择为维保类型！')
                return
            }
            let json = {
                'type': this.formData.maintenanceLog.maintenanceType,
                'ids': [this.formData.maintenanceLog.maintenancePlanId]
            }
            selectMaintenance(json).then(res=>{
                if(this.formData.maintenanceLog.maintenancePlan !== res.billNo) {
                    this.clientPop('info', '切换单据后维保明细将被清空，请确认！', ()=>{
                        this.formData.maintenanceLog.maintenancePlan = res[0].billNo
                        this.formData.maintenanceLog.maintenancePlanId = res[0].billId
                        this.clearDetail()
                    })
                }
            })
        },
        //==========设备维修清单===========
        //判断当前状态是否已修改
        curStateChange (row) {
            this.currentRow = row
            if (row.maintenanceLogDtlId) {
                if(row.newAdd) {
                    this.currentRow.changeType = 1
                }else{
                    this.currentRow.changeType = 2
                }
            }
            this.onAmont(row)
        },
        //设备维修清单-维保费用（元） = 材料费（元）+人工费（元）+辅助设备费（元） 保留两位小数
        onAmont (row) {
            row.maintenanceFee = count.onMaintenanceFeet(+row.materialsFee, +row.artificialFee, +row.assistFee) //设备维修清单-维保费用（元）
            this.formData.maintenanceLog.auxiliaryFee = count.onBaseAuxiliaryFee(this.maintenanceLogDtlList) //基础信息-辅助设备费（元）
            this.formData.maintenanceLog.maintenancePrice = count.onBaseMaintenancePrice(this.maintenanceLogDtlList) //基础信息-维保费（元）
        },
        /**选择设备 */
        async selectEquip ( ) {
            let ids = []
            ids = this.maintenanceLogDtlListCopy.map(x=>x.maintenancePlanId)
            let json = {
                'ids': ids,
                'billid': this.formData.maintenanceLog.maintenancePlanId
            }
            selectMaintenanceDtl(json).then(res=>{
                res.forEach(item=>{
                    item.materialsFee = null
                    let obj = {
                        'artificialFee': null,
                        'assistFee': null,
                        'billId': this.billid,
                        'billNo': '',
                        'categoryId': '',
                        'categoryName': '',
                        'changeType': 1,
                        'equipmentId': '',
                        'equipmentName': '',
                        'equipmentNo': '',
                        'info': '',
                        'maintenanceFee': null,
                        'maintenanceLogDtlId': '',
                        'manufacturer': '',
                        'materialsDtlDTO': {
                            'artificialFeeList': [],
                            'materialsDtlList': [],
                            'technologyParameterList': []
                        },
                        'materialsFee': null,
                        'specificationModel': '',
                        'useNum': null,
                        'newAdd': null,
                        'maintenancePlanId': item.id,
                        ...item
                    }
                    //前端生成id
                    this.$Ajax
                        .httpGet({
                            url: '/uid/builder?num=1',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            }
                        })
                        .then(res=>{
                            obj.maintenanceLogDtlId = res[0]
                            obj.newAdd = true //表示新增的数据
                            this.defaultShowFirstLine()
                        })
                    this.maintenanceLogDtlListCopy.push(obj)
                    this.maintenanceLogDtlList.push(obj)
                })
                this.maintenanceLogDtlListCopy = removeRepetition({
                    'arr': this.maintenanceLogDtlListCopy,
                    'id': 'maintenancePlanId'
                })
                this.maintenanceLogDtlList = removeRepetition({
                    'arr': this.maintenanceLogDtlList,
                    'id': 'maintenancePlanId'
                })
            })

        },
        //判读选择中的是那行
        rowClick (row) {
            this.currentMaintenanceRow = row
            if(this.onlyID === row.maintenanceLogDtlId) return
            this.onlyID = row.maintenanceLogDtlId
        },
        //选择行颜色
        rowStyle ({ row }) {
            if(!this.onlyID)return
            if(this.onlyID === row.maintenanceLogDtlId) {
                return {
                    'background-color': 'rgb(179,210,238)!important'
                }
            }
        },
        //单个删除维修清单
        handlePlanDetailDelete (row, $index) {
            this.clientPop('info', this.oneDeleteErr, ()=>{
                let length = this.errorMsg.length
                this.maintenanceLogDtlListCopy.splice($index, 1)
                if(row.maintenanceLogDtlId) {
                    this.$set(this.maintenanceLogDtlList[$index], 'changeType', -1)
                }else{
                    this.maintenanceLogDtlList.splice($index, 1)
                }
                //清空子数据
                for(let i in this.currentMaintenanceRow.materialsDtlDTO) {
                    this.currentMaintenanceRow.materialsDtlDTO[i] = []
                }
                this.onAmont(row)
                this.defaultShowFirstLine() //默认显示第一行
                if (length > 0 ) {
                    this.verifyTable()
                }
            })
        },
        //获取维修清单明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //删除明细列表
        deletePlanList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.delete
                )
            }
        },
        delete () {
            let length = this.errorMsg.length
            this.planSelect.filter(row=>{
                //清空子数据
                for(let i in row.materialsDtlDTO) {
                    row[i] = []
                }
                //清空子数据
                for(let i in this.currentMaintenanceRow.materialsDtlDTO) {
                    this.currentMaintenanceRow.materialsDtlDTO[i] = []
                }
                this.onAmont(row)
                this.maintenanceLogDtlListCopy.map((x, index)=>{
                    if(row == x ) {
                        this.maintenanceLogDtlListCopy.splice(index, 1)
                    }
                })
                if(row.maintenanceLogDtlId) {
                    const index = this.maintenanceLogDtlList.findIndex(item=>{
                        return item.maintenanceLogDtlId == row.maintenanceLogDtlId
                    })
                    this.$set(this.maintenanceLogDtlList[index], 'changeType', -1)
                }else{
                    this.maintenanceLogDtlList.map((x, index)=>{
                        if(row == x ) {
                            this.maintenanceLogDtlList.splice(index, 1)
                        }
                    })
                }
                if (length > 0 ) {
                    this.verifyTable()
                }
                this.defaultShowFirstLine() //默认显示第一行
                this.$refs.planTable.clearSelection()
            })
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.maintenanceLogDtlListCopy.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        if(item.info === null || item.info === '') {
                            let str = `请填写第 ${index + 1} 行的（维保内容）`
                            this.errorMsg.push(str)
                        }
                    }
                })
                if(this.errorMsg.length > 0) {
                    reject()
                }else{
                    resolve()
                }
            })
        },
        //===========设备维修内容=============
        /**从机械发料引入 */
        selectStoreIssue () {
            if(this.maintenanceLogDtlListCopy.length === 0) {
                this.clientPop(
                    'err',
                    '设备维修清单不能为空！',
                )
                return
            }
            let ids = []
            if(this.currentMaintenanceRow.materialsDtlDTO.materialsDtlList.length > 0 ) {
                ids =  this.currentMaintenanceRow.materialsDtlDTO.materialsDtlList.map(item=>{
                    let obj = {
                        'materialClassId': item.materialClassId,
                        'materialId': item.materialId,
                        'spec': item.specification,
                        'texture': item.texture
                    }
                    return JSON.stringify(obj) //已选参数
                })
            }
            let json = {
                'ids': ids,
                'type': {
                    'equipNumber': this.currentMaintenanceRow.equipmentNo,
                    'orgId': this.formData.maintenanceLog.orgId
                }
            }
            selectStoreIssue(json).then(res=>{
                res.forEach(item=>{
                    let obj = {
                        'changeType': 1,
                        'id': '',
                        'maintenanceLogDtlId': this.onlyID,
                        'maintenanceLogId': '',
                        'materialDtlId': '',
                        'materialName': '',
                        'num': item.collectedQuantity,
                        'price': null,
                        'replaceReason': '',
                        'specification': item.spec,
                        'sum': null,
                        'unit': '',
                        'oldNum': item.collectedQuantity,
                        'source': 0, //0 机械 1物资
                        'materialClassId': '',
                        'materialId': '',
                        'texture': item.texture,
                        ...item
                    }
                    this.currentMaintenanceRow.materialsDtlDTO.materialsDtlList.push(obj)
                })
                this.itemObj = {}
                this.currentMaintenanceRow.materialsDtlDTO.materialsDtlList = this.currentMaintenanceRow.materialsDtlDTO.materialsDtlList.reduce((item, next)=>{
                    if(next.changeType == -1) {
                        item.push(next)
                    }else{
                        if(!this.itemObj[next.materialClassId] || !this.itemObj[next.materialId] || !this.itemObj[next.texture]) {
                            item.push(next)
                            this.itemObj[next.materialClassId] = true
                            this.itemObj[next.materialId] = true
                            this.itemObj[next.texture] = true
                        }
                    }
                    return item
                }, [])
            })
        },
        //从物资库引入
        selectMaterials () {
            if(this.maintenanceLogDtlListCopy.length === 0) {
                this.clientPop(
                    'err',
                    '设备维修清单不能为空！',
                )
                return
            }
            categoryLibrary().then(res=>{
                res.forEach(item=>{
                    let obj = {
                        'changeType': 1,
                        'id': '',
                        'maintenanceLogDtlId': this.onlyID,
                        'maintenanceLogId': '',
                        'materialDtlId': '',
                        'materialName': item.materialName,
                        'num': null,
                        'price': null,
                        'replaceReason': '',
                        'specification': item.spec,
                        'sum': null,
                        'unit': item.unit,
                        'oldNum': null,
                        'source': 1 //0 机械 1物资
                    }
                    this.currentMaintenanceRow.materialsDtlDTO.materialsDtlList.push(obj)
                })

            })
        },
        //设备维修内容列表新增
        addPlanChildInfo (feild) {
            if(this.maintenanceLogDtlListCopy.length === 0) {
                this.clientPop(
                    'err',
                    '设备维修清单不能为空！',
                )
                return
            }
            switch(feild)
            {
            case 'artificialFeeList':  //人工费
                {
                    const obj = {
                        'artificialFeeId': '',
                        'billId': '',
                        'fee': null,
                        'maintenanceLogDtlId': this.onlyID,
                        'maintenanceProject': '',
                        'changeType': 1
                    }
                    this.currentMaintenanceRow.materialsDtlDTO.artificialFeeList.push(obj)
                }
                break
            case 'technologyParameterList':  //技术参数
                {
                    const obj =  {
                        'bigItemName': '',
                        'changeType': 1,
                        'leaveFactoryNo': '',
                        'maintenanceLogDtlId': this.onlyID,
                        'maintenanceLogId': '',
                        'manufactureUnit': '',
                        'producedDate': '',
                        'technologyParameterId': ''
                    }
                    // let date  = formatDate(new Date(), 'yyyy-MM-dd')
                    // obj.producedDate = date
                    this.currentMaintenanceRow.materialsDtlDTO.technologyParameterList.push(obj)
                }
                break
            }
        },
        //物资明细当前状态
        curMaterialsDtlStateChange (row, name) {
            if(row.source === 0) {
                if(row.num > row.oldNum) {
                    this.clientPop(
                        'err',
                        '不能超过机械发料数量！',
                    )
                    row.num = row.oldNum
                }
            }
            if (row.materialDtlId) {
                row.changeType = 2
            }
            this.onCountMaterialsPrice(row)
            if(name) {
                this.onCountMaterialsFee(this.currentMaintenanceRow.materialsDtlDTO[name])
            }
            this.onAmont(this.currentMaintenanceRow) //设备维修清单-维保费用（元）
        },
        //计算材料费（元）
        onCountMaterialsFee (rowArr) {
            this.currentMaintenanceRow.materialsFee = count.onUpCollect(rowArr) //设备维修清单-材料费（元）
            this.formData.maintenanceLog.materialsPrice = count.onBaseUpCollect(this.maintenanceLogDtlList) //基础信息-材料费
        },
        //计算物资明细单价
        onCountMaterialsPrice (row) {
            row.price = count.onMaterialsDtlPrice(+row.sum, +row.num) //物资明细单价
        },
        //技术参数当前状态
        curTechnologyStateChange (row) {
            if (row.technologyParameterId) {
                row.changeType = 2
            }
        },
        //人工费当前状态
        curManpowerStateChange (row, name) {
            if (row.artificialFeeId) {
                row.changeType = 2
            }
            if(name) {
                this.onCountArtificialFee(this.currentMaintenanceRow.materialsDtlDTO[name])
            }
            this.onAmont(this.currentMaintenanceRow)
        },
        //计算人工费
        onCountArtificialFee (rowArr) {
            this.currentMaintenanceRow.artificialFee = count.onArtificialFee(rowArr) //设备维修清单-人工费（元）
            this.formData.maintenanceLog.manpowerPrice = count.onBaseArtificialFee(this.maintenanceLogDtlList)  //基础信息-人工费（元）
        },
        //如果是-1就隐藏  物资明细
        materialsRowClass ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //如果是-1就隐藏  技术参数
        technologyRowClass ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //如果是-1就隐藏  人工费
        artificialFeeRowClass ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //单个删除设备维修内容列表
        handleDelete (row, $index, feild, id) {
            let arr = this.currentMaintenanceRow.materialsDtlDTO[feild]
            this.clientPop('info', this.oneDeleteErr, ()=>{
                if(row[id]) {
                    this.$set(arr[$index], 'changeType', -1)
                }else{
                    arr.splice($index, 1)
                }
                switch(feild) {
                case 'materialsDtlList': //物资明细
                    this.onCountMaterialsPrice(arr)
                    this.onCountMaterialsFee(arr)
                    this.onAmont(this.currentMaintenanceRow)
                    break
                case 'artificialFeeList':  //人工费
                    this.onCountArtificialFee(arr)
                    this.onAmont(this.currentMaintenanceRow)
                    break
                }
                let length = this.errorMaterialMsg.length || this.errortechnicalMsg.length || this.errorArtificialMsg.length
                if (length > 0 ) {
                    this.verifyMaterialTable()
                }
            })
        },
        //获取设备维修内容列表的选择项
        planTableChildSelect (selection, feild) {
            this['planSelect' + feild] = selection
        },
        //删除设备维修内容列表
        deletePlanChildList (feild, id) {
            const length = this['planSelect' + feild].length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    ()=>{
                        let arr = this.currentMaintenanceRow.materialsDtlDTO[feild]
                        this['planSelect' + feild].filter(row=>{
                            if(row[id]) {
                                const index = arr.findIndex(item=>{
                                    return item[id] == row[id]
                                })
                                this.$set(arr[index], 'changeType', -1)
                            }else{
                                arr.map((x, index)=>{
                                    if(row == x ) {
                                        arr.splice(index, 1)
                                    }
                                })
                            }
                            switch(feild) {
                            case 'materialsDtlList': //物资明细
                                this.onCountMaterialsPrice(arr)
                                this.onCountMaterialsFee(arr)
                                this.onAmont(this.currentMaintenanceRow)
                                break
                            case 'artificialFeeList':  //人工费
                                this.onCountArtificialFee(arr)
                                this.onAmont(this.currentMaintenanceRow)
                                break
                            }
                            let length = this.errorMaterialMsg.length || this.errortechnicalMsg.length || this.errorArtificialMsg.length
                            if (length > 0 ) {
                                this.verifyMaterialTable()
                            }
                            this.$refs['planTable' + feild].clearSelection()
                        })
                    },

                )
            }
        },
        //设备维修内容非空验证
        verifyMaterialTable () {
            return new Promise((resolve, reject)=>{
                this.errorMaterialMsg = []  //物资明细
                this.errortechnicalMsg = [] //技术参数
                this.errorArtificialMsg = [] //人工费
                // 设备xxxxx物资明细/技术参数/人工费未填写完整，请检查
                this.maintenanceLogDtlListCopy.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        let flagMaterial = item.materialsDtlDTO.materialsDtlList.some(x=>{
                            if(x.changeType !== -1) {
                                return x.num === null || x.num === '' || x.sum === null || x.sum === '' || x.replaceReason === null || x.replaceReason === ''
                            }
                        })
                        if(flagMaterial) {
                            let str = `第${index + 1}行设备编号为${item.equipmentNo}物资明细未填写完整，请检查！`
                            this.errorMaterialMsg.push(str)
                        }
                        let flagTechnology = item.materialsDtlDTO.technologyParameterList.some(x=>{
                            if(x.changeType !== -1) {
                                return x.bigItemName === null || x.bigItemName === '' || x.leaveFactoryNo === null || x.leaveFactoryNo === '' || x.manufactureUnit === null || x.manufactureUnit === '' || x.producedDate === null || x.producedDate === ''
                            }
                        })
                        if(flagTechnology) {
                            let str = `第${index + 1}行设备编号为${item.equipmentNo}技术参数未填写完整，请检查！`
                            this.errortechnicalMsg.push(str)
                        }
                        let flagArtificial = item.materialsDtlDTO.artificialFeeList.some(x=>{
                            if(x.changeType !== -1) {
                                return x.maintenanceProject === null || x.maintenanceProject === '' || x.fee === null || x.fee === ''
                            }
                        })
                        if(flagArtificial) {
                            let str = `第${index + 1}行设备编号为${item.equipmentNo}人工费未填写完整，请检查！`
                            this.errorArtificialMsg.push(str)
                        }
                    }
                })
                this.errorMaterialMsg.length > 0 || this.errortechnicalMsg.length > 0 || this.errorArtificialMsg.length > 0 ? reject() : resolve()
            })
        },
        //============按钮操作=============
        /**更新基本信息 */
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.form.validate(valid => {
                    if(valid) {
                        request.maintenanceRecordsUpdate(this.formData).then(()=>{
                            resolve()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                            this.scorllError()
                        })
                    }else{
                        reject()
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新明细
        updateDetailInfo () {
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    this.verifyMaterialTable().then(()=>{
                        request.maintenanceRecordsDtlUpdate(this.maintenanceLogDtlList).then(()=>{
                            this.$refs.form.validate(valid => {
                                if(valid) {
                                    request.maintenanceRecordsUpdate(this.formData).then(()=>{
                                        resolve()
                                    }).catch(err=>{
                                        reject(err)
                                        this.setError('baseInfo')
                                        this.scorllError()
                                    })
                                }else{
                                    reject()
                                    this.setError('baseInfo')
                                    this.scorllError()
                                    return false
                                }
                            })
                        }).catch(err=>{
                            reject(err)
                            this.setError('planDetail')
                            this.scorllError()
                        })
                    }).catch(err=>{
                        this.setError('planDetail')
                        reject(err)
                        this.scorllError()
                    })
                }).catch(err=>{
                    this.setError('planDetail')
                    reject(err)
                    this.scorllError()
                })

            })
        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            const requestFn = ()=>{
                return [
                    this.updateDetailInfo()
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            if(this.maintenanceLogDtlListCopy.length === 0) {
                let str = '设备维修清单不能为空！'
                this.errorMsg.push(str)
                this.setError('planDetail')
                this.scorllError()
                return
            }
            const requestFn = ()=>{
                return [
                    this.updateDetailInfo()
                ]
            }
            submitCommit(this, requestFn, 2)
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 2)
        },
        //删除
        deleteBills () {
            this.clientPop('info', this.oneDeleteErr, ()=>{
                request.maintenanceRecordsDelete({ listId: this.billid }).then(()=>{
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/maintenanceRecordsList')
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
.childTab{
    ::v-deep .el-tabs__header{
        position: absolute!important;
    }
    ::v-deep .el-tabs__content{
        padding: 0 0 0 20px!important;
    }
}
.childTab1{
    ::v-deep .el-tabs__header{
        position: absolute!important;
        .el-tabs__nav-scroll{
            position: relative;
            .el-tabs__nav{
                position: fixed;
                top: 0;
                width: 190px;
            }
        }
    }
}
.childTab2{
    ::v-deep .el-tabs__header{
        position: absolute!important;
        .el-tabs__nav-scroll{
            position: relative;
            .el-tabs__nav{
                position: absolute;
                bottom: 0;
                width: 100%;
            }
        }
    }
}
</style>
